package com.luoran.bartalks.core.config;

import java.nio.charset.Charset;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import com.luoran.bartalks.core.AppSessionInterceptor;
import com.luoran.bartalks.core.SessionInterceptor;

/**
 * @author lifetime
 *
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(WebConfig.class);

    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(new SessionInterceptor());
        registration.addPathPatterns("/**");
        registration.excludePathPatterns("/api/**", "/user/**", "/", "/error");
        registry.addInterceptor(new AppSessionInterceptor()).addPathPatterns("/api/**");
        super.addInterceptors(registry);
    }

    @Configuration
    @ConditionalOnClass({ FastJsonHttpMessageConverter4.class })
    @ConditionalOnProperty(name = {
            "spring.http.converters.preferred-json-mapper" }, havingValue = "fastjson", matchIfMissing = true)
    protected static class FastJson2HttpMessageConverterConfiguration {

        protected FastJson2HttpMessageConverterConfiguration() {
        }

        @Bean
        @ConditionalOnMissingBean({ FastJsonHttpMessageConverter4.class })
        public FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter() {
            FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setCharset(Charset.forName("UTF-8"));
            fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);

            converter.setFastJsonConfig(fastJsonConfig);

            converter.setSupportedMediaTypes(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
            return converter;
        }
    }

    @Bean
    public HandlerExceptionResolver customerExceptionPage() {
        HandlerExceptionResolver exceptionResolver = new HandlerExceptionResolver() {
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                    Object handler, Exception ex) {
                ModelAndView mav = new ModelAndView("/error-500");
                log.error(ex.getMessage(), ex.fillInStackTrace());
                mav.addObject("errorMsg", ex.toString());
                return mav;
            }
        };
        return exceptionResolver;
    }

    @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        return characterEncodingFilter;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(1024 * 1024 * 10);
        return factory.createMultipartConfig();
    }

}
